package com.junxonline.instant.admin.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.google.gson.reflect.TypeToken;
import com.junxonline.instant.dao.entity.model.device.Terminal;
import com.junxonline.instant.dao.entity.model.logDevice.LogDeviceOperation;
import com.junxonline.instant.dao.mapper.device.TerminalMapper;
import com.junxonline.instant.dao.mapper.logDevice.LogDeviceOperationMapper;
import com.junxonline.instant.common.constant.DataSourceConstant;
import com.junxonline.instant.common.constant.RedisMqChannelConstant;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 终端操作日志消费者
 *
 * @author JunX
 * @date 2021-11-16
 */
@Log4j2
@Component
public class LogDeviceOperationListener implements MessageListener {

    @Autowired
    private LogDeviceOperationMapper logDeviceOperationMapper;

    @Autowired
    private TerminalMapper terminalMapper;

    /**
     * 消息处理
     *
     * @param message 消息
     */
    @Override
    @DS(DataSourceConstant.SHARDING)
    public void onMessage(Message message, byte[] pattern) {
        RedisSerializer serializer = new GenericJackson2JsonRedisSerializer();
        String msg = (String) serializer.deserialize(message.getBody());
        log.info("收到频道[" + RedisMqChannelConstant.KEY_REDIS_MSG_CHANNEL_LOG_DEVICE_OPERATION + "]消息 => {}", msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        List<Long> ids = jsonObject.getObject("ids", new TypeToken<List<Long>>(){}.getType());
        LogDeviceOperation logDeviceOperation = jsonObject.getObject("logDeviceOperation", LogDeviceOperation.class);
        for (Long id : ids) {
            Terminal terminal = terminalMapper.selectById(id);
            if (terminal != null) {
                logDeviceOperation.setOrganizationId(terminal.getOrganizationId());
                logDeviceOperation.setTerminalCode(terminal.getCode());
                logDeviceOperationMapper.insert(logDeviceOperation);
            }
        }
    }

}